import { createStore } from 'vuex';
import { getCartProducts } from '@/api/cart';

export default createStore({
  state: {
    currentUser: null,
    cartItems: [],
    cartLoading: false,
    networkError: false
  },
  mutations: {
    setCurrentUser(state, user) {
      state.currentUser = user;
    },
    clearCurrentUser(state) {
      state.currentUser = null;
      // 清空购物车数据
      state.cartItems = [];
    },
    setCartItems(state, items) {
      state.cartItems = items;
    },
    setCartLoading(state, loading) {
      state.cartLoading = loading;
    },
    setNetworkError(state, error) {
      state.networkError = error;
    },
    updateCartItemQuantity(state, { cartId, quantity }) {
      const item = state.cartItems.find(item => item.cartId === cartId);
      if (item) {
        item.quantity = quantity;
      }
    },
    removeCartItem(state, cartId) {
      state.cartItems = state.cartItems.filter(item => item.cartId !== cartId);
    },
    addCartItem(state, item) {
      // 检查是否已存在相同商品
      const existingItem = state.cartItems.find(cartItem => cartItem.productId === item.productId);
      if (existingItem) {
        // 如果存在，更新数量
        existingItem.quantity += item.quantity;
      } else {
        // 如果不存在，添加新商品
        state.cartItems.push(item);
      }
    }
  },
  actions: {
    login({ commit }, user) {
      commit('setCurrentUser', user);
    },
    logout({ commit }) {
      commit('clearCurrentUser');
    },
    async fetchCartItems({ commit, state }) {
      if (!state.currentUser) {
        return;
      }
      try {
        commit('setCartLoading', true);
        commit('setNetworkError', false);
        const response = await getCartProducts(state.currentUser.userId);
        if (response.status === 'success') {
          const cartItems = response.data.map(item => ({
            cartId: item.cartId,
            userId: item.userId,
            productId: item.productId,
            quantity: item.quantity,
            productName: item.productName,
            sellingPrice: parseFloat(item.sellingPrice),
            productImg: item.productImg,
            specification: item.specification || '默认规格'
          }));
          commit('setCartItems', cartItems);
        }
      } catch (error) {
        console.error('获取购物车数据失败:', error);
        if (error.code === 'ERR_NETWORK' || (error.message && error.message.includes('Network Error'))) {
          commit('setNetworkError', true);
          console.error('网络连接错误 - 请检查后端服务是否启动');
        } else {
          commit('setNetworkError', false);
        }
      } finally {
        commit('setCartLoading', false);
      }
    }
  },
  getters: {
    isAuthenticated: state => !!state.currentUser,
    user: state => state.currentUser,
    cartItemCount: state => state.cartItems.length,
    cartTotalQuantity: state => state.cartItems.reduce((total, item) => total + item.quantity, 0),
    cartTotalPrice: state => state.cartItems.reduce((total, item) => total + (item.sellingPrice * item.quantity), 0),
    hasNetworkError: state => state.networkError
  }
});
